package com.dhcc.DRGsHosp.facade.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.inject.Named;

import org.apache.commons.io.IOUtils;

import com.dhcc.DRGsHosp.facade.ReStartServiceFacade;

/**
 * @title		: ReStartServiceFacadeImpl.java 
 * @description	: 
 * @author		: chl
 * @date		: 2017年3月14日
 * @version     : 2017
 * @copyright   : DHCC 
 */
@Named("drgsHospFacadeImpl42")
public class ReStartServiceFacadeImpl implements ReStartServiceFacade {

	@Override
	public void addFile(String fileRealPath, String filePath) {
		deleteFile(filePath);
		try {
			FileInputStream fis = new FileInputStream(fileRealPath);
			FileOutputStream fos = new FileOutputStream(filePath + "\\donghua.p12");
			BufferedInputStream bInputStream = new BufferedInputStream(fis);
			BufferedOutputStream bOutputStream = new BufferedOutputStream(fos);
			int temp = 0;
			while((temp=bInputStream.read()) != -1) {
				bOutputStream.write(temp);
			}
			bOutputStream.flush();
			bOutputStream.close();
			bInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteFile(String filePath) {
		 File file = new File(filePath + "\\donghua.p12");
         if(file.exists()&&file.isFile())
             file.delete();
	}


	@Override
	public boolean stop(String order,String filePath) {
		// 判断服务是否开启
		if(!isServiceStarted()) {
			return true ;
		}
		Runtime rt = Runtime.getRuntime();
		Process ps = null;
		try {
			ps = rt.exec(order);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			ps.waitFor();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ps.destroy();
		ps = null;
		int j = 0 ;
		// 判断服务是否成功关停
		while(j<10) {
			if(!isServiceStarted()) {
				return true ;
			}else{
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e ) {
					e.printStackTrace();
				}
				j++ ;
			}
		}
		return false;
	}

	@Override
	public boolean isServiceStarted() {
		boolean flag=false;
		try{
			Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
			InputStream os = p.getInputStream();
			String s = IOUtils.toString(os) ;
			if(s.indexOf("DrgService.exe")>=0){
				flag=true;
			}
			else{
				flag=false;
			}
		}catch(java.io.IOException ioe) {
			ioe.printStackTrace();
		}
		return flag ;
	}
}
